package redis

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"gogame/logger"
)

type Pipeline struct {
	pipeline redis.Pipeliner
	ctx      context.Context
	ver      string
}

type PipelineInterface interface {
	Pipeline() redis.Pipeliner
}

func NewPipeline(client PipelineInterface, ver string) *Pipeline {
	return &Pipeline{
		pipeline: client.Pipeline(),
		ctx:      context.Background(),
		ver:      ver,
	}
}

// Del 删除key
func (p *Pipeline) Del(key string) *redis.IntCmd {
	return p.pipeline.Del(p.ctx, key)
}

// HGetAll 获取哈希key的所有kv
func (p *Pipeline) HGetAll(key string) *redis.StringStringMapCmd {
	return p.pipeline.HGetAll(p.ctx, key)
}

// HMSet 设置哈希key的多个值
func (p *Pipeline) HMSet(key string, val any) error {
	setMapData, err := CheckHMSetVal(val)
	if err != nil {
		err = fmt.Errorf("redis.pipeline(%s) HMSet val err!!\nkey: %s  val: %v \nerr-->%s\n", p.ver, key, err, val)
		logger.WorkerLog.Warn(err.Error())
		return err
	}

	_, err = p.pipeline.HMSet(p.ctx, key, setMapData).Result()
	if err != nil {
		err = fmt.Errorf("redis.pipeline(%s) HMSet fail!!\nkey: %s\nerr-->%s\n", p.ver, key, err)
		logger.WorkerLog.Warn(err.Error())
	}

	return err
}

// Exec 执行管道内所有命令
func (p *Pipeline) Exec() ([]redis.Cmder, error) {
	_cmderList, err := p.pipeline.Exec(p.ctx)
	return _cmderList, err
}
